#include "networkwindow.h"
#include "ui_networkwindow.h"

NetWorkWindow::NetWorkWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::NetWorkWindow)
{
    ui->setupUi(this);
    initIPAddress();
//    packJson();
//    parseJson();
}

NetWorkWindow::~NetWorkWindow()
{
    delete ui;
}

void NetWorkWindow::initIPAddress()
{
    if(ui->comboBox->currentText() == "TCP Client")
    {
        ui->ipCombox->setEditable(true);
    }
    else
    {
        ui->ipCombox->setEditable(false);
        //获取本地主机名
        QString localName = QHostInfo::localHostName();
        //获取QHostInfo对象
        QHostInfo info = QHostInfo::fromName(localName);
        //获取QHostAddress对象
        QList<QHostAddress> addrs = info.addresses();

        //遍历主机信息
        for(const auto & addr : addrs)
        {
            //过滤IPV4
            if(addr.protocol() == QAbstractSocket::IPv4Protocol)
            {
                //将主机地址转换为点分十进制
                ui->ipCombox->addItem(addr.toString());
            }
        }
    }
}

//组包
QByteArray NetWorkWindow::packJson()
{
    QJsonObject jsonObj;
    jsonObj.insert("shen","shanxi");
    jsonObj.insert("shi","shanxi");

    root.insert("name","lanxiao");
    root.insert("age",24);
    root.insert("addr",jsonObj);

    QJsonArray scoreArray;
    scoreArray.append(90);
    scoreArray.append(80);
    scoreArray.append(97);

    QJsonDocument doc(root);
    return doc.toJson();
}

//解包
void NetWorkWindow::parseJson(QByteArray text)
{
    //QByteArray text = "{\"age\":24,\"name\":\"lanxiao\"}";

    QJsonDocument doc = QJsonDocument::fromJson(text);

    QJsonObject root = doc.object();
    QJsonValue addrval = root.value("addr");
    QJsonObject addObj = addrval.toObject();

    QJsonValue str =  root.value("name");
    QJsonValue arr =  root.value("age");
    QJsonValue score =  root.value("score");

    QJsonValue shen =  addObj.value("shen");
    QJsonValue shi =  addObj.value("shi");

    QJsonArray sc = score.toArray();
    int size = sc.size();
    for(int i = 0; i< size; ++i)
    {
        qDebug()<<sc[i];
    }

    qDebug()<<str.toString()<<" "<<arr.toInt();
    qDebug()<<shen.toString()<<" "<<shi.toString();
}

void NetWorkWindow::on_pushButton_clicked()
{
    if(ui->comboBox->currentText() == "TCP Server")
    {
        if(ui->pushButton->text() == "打开")
        {
            ui->pushButton->setText("关闭");
            //该按钮功能为启动监听
            s_socket = new QTcpServer(this);
            bool isListen = s_socket->listen(QHostAddress(ui->ipCombox->currentText()),ui->lineEdit->text().toInt());
            if(isListen)
            {
                ui->infoMes->setText("监听已启动");
                //获取通信套接字
                connect(s_socket,&QTcpServer::newConnection,[=](){
                    ui->infoMes->setText("客户端建立连接");
                    c_socket = s_socket->nextPendingConnection();
                    connect(c_socket,&QTcpSocket::readyRead,[=](){
                        ui->textEdit->append(c_socket->readAll());
                    });

                    connect(c_socket,&QTcpSocket::disconnected,[=](){
                        ui->infoMes->setText("客户端断开连接");
                        c_socket->deleteLater();
                    });

                });
            }
        }
        else
        {
           ui->pushButton->setText("打开");
           ui->infoMes->setText("监听已关闭");
           s_socket->close();
        }
    }
    else if(ui->comboBox->currentText() == "TCP Client")
    {
        if(ui->pushButton->text() == "打开")
        {
            ui->pushButton->setText("断开");
            client_socket = new QTcpSocket(this);
            client_socket->connectToHost(QHostAddress(ui->ipCombox->currentText()),ui->lineEdit->text().toInt());

            connect(client_socket,&QTcpSocket::connected,[=](){
                ui->infoMes->setText("已连接到远程主机");
                connect(client_socket,&QTcpSocket::readyRead,[=](){
                    ui->textEdit->append(client_socket->readAll());
                });
            });
        }
        else
        {
            ui->pushButton->setText("打开");
            client_socket->disconnectFromHost();
             ui->infoMes->setText("已断开连接");
            client_socket->deleteLater();
        }
    }
    else if(ui->comboBox->currentText() == "UDP")
    {
        if(ui->pushButton->text() == "打开")
        {
            ui->pushButton->setText("断开");
            u_socket = new QUdpSocket(this);
            //绑定
            bool isBind = u_socket->bind(QHostAddress(ui->ipCombox->currentText()),ui->lineEdit->text().toInt());
            if(isBind)
            {
                ui->infoMes->setText("绑定成功");
            }
            connect(u_socket,&QUdpSocket::readyRead,[=](){
                QByteArray res;
                qint32 size =  u_socket->pendingDatagramSize();
                res.resize(size);

                QHostAddress ip;
                quint16 port;
                u_socket->readDatagram(res.data(),size,&ip,&port);
                parseJson(res);
                ui->textEdit->append(QString("[ip:%1,port:%2] ").arg(ip.toString()).arg(port) + res);
            });
        }
        else
        {
            ui->pushButton->setText("打开");
            u_socket->disconnectFromHost();
            ui->infoMes->setText("已断开连接");
            u_socket->deleteLater();
        }

    }
}

void NetWorkWindow::on_sendPushButton_clicked()
{
    //获取文本框内容
    QString text = ui->sendEdit->toPlainText();
    if(ui->comboBox->currentText() == "TCP Server")
    {
        //发送给客户端
        c_socket->write(text.toUtf8());
    }
    else if(ui->comboBox->currentText() == "TCP Client")
    {
        client_socket->write(text.toUtf8());
    }
    else
    {
        QByteArray text = packJson();
        u_socket->writeDatagram(text,QHostAddress(ui->ipLineEdit->text()),ui->portLineEdit->text().toInt());
    }

}

void NetWorkWindow::on_clearTxtButton_clicked()
{
    ui->textEdit->clear();
}
